<template>
  <div :id="id"></div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import { createQrCode } from "@/libs";
import { getScanCodeUrl } from "@/api/sign";
import { getUrl } from "@/api/group/group";

const APPID = process.env.VUE_APP_APPID;

@Component
export default class ScanQrcode extends Vue {
  @Prop({ default: "qrcode" }) id!: string;

  @Prop({ default: "400px" }) height!: string;

  @Prop({
    default: "redirect",
    required: true,
  })
  redirectUrl!: string;

  @Prop({
    default: "AccountSwitching",
    required: true,
  })
  scenes!: string;

  @Prop({
    default: null,
  })
  shopInfoId!: number;

  url = "";

  async created() {
    await this.getCompleteUrl();
    createQrCode({
      id: this.id,
      url: this.url,
      height: this.height,
    });
  }

  async getShopTemplateUrl() {
    let result = "";
    try {
      const response = await getUrl({});
      const { data, code } = response;
      if (code === 200) {
        result = data.pcTerminaUrl;
      }
    } catch (e) {
      this.$message({
        type: "warning",
        message: e,
      });
    }
    return result;
  }

  async getCompleteUrl() {
    try {
      const pcTerminaUrl = await this.getShopTemplateUrl();
      if (pcTerminaUrl) {
        const redirectUrl = pcTerminaUrl + this.redirectUrl;
        const response = await getScanCodeUrl({
          shopInfoId: this.shopInfoId,
          appId: APPID,
          redirectUrl,
          scenes: this.scenes,
        });
        const { data, code } = response;
        if (code === 200) {
          this.url = data;
        } else {
          this.$message({
            type: "warning",
            message: "获取跳转链接失败！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "跳转域名获取失败！",
        });
      }
    } catch (e) {
      this.$message({
        type: "warning",
        message: e,
      });
    }
  }
}
</script>

<style></style>
